/**
 * Filename: UserStatusActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/12 17:47
 */
package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.TimeLineStatusAdapter;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.bean.YNUserData;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 用户动态列表信息
 */
public class UserStatusActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener {
    private Toolbar mToolbar;
    private TextView mToolbarTitle;
    private RecyclerView rv_user_status_list;
    private WrapContentLinearLayoutManager mLinearLayoutManager;
    private SimpleDraweeView mUserStatusBG;
    private SimpleDraweeView iv_user_status_avatar;
    private TextView tv_user_status_nickname;
    private TextView tv_user_status_msg;
    private ImageView iv_user_status_sex;
    private TimeLineStatusAdapter mAdapter;
    public AppBarLayout mAppBar;
    private int mGroupId;
    private int mUserId;
    private boolean isBottom;
    private boolean aIsMe;
    private boolean aIsChat;
    private String noteName;
    private SwipeRefreshLayout mRefreshlayout;
    private Handler handler = new Handler();
    private CollapsingToolbarLayout collapsing_user_status_toolbar;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    public static String avatarPic;
    public static String nickname;
    private TextView right;
    private boolean refresh = false;
    private List<YNStatus> groupStatusItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_user_status);
        init();
        initView();
    }

    private void init() {
        registerBoradcastReceiver();
        aIsChat = getIntent().getBooleanExtra(CommonConstants.YNISCHAT, false);
        noteName = getIntent().getStringExtra(CommonConstants.YNUSERNOTENAME);
        aIsMe = getIntent().getBooleanExtra(CommonConstants.YNISME, false);
        mUserId = getIntent().getIntExtra(CommonConstants.YNUSERID, 0);
        mGroupId = getIntent().getIntExtra(CommonConstants.YNGROUPID, 0);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit(mUserId, mGroupId, 0);
            }
        }, 500);
        getUserTop(mUserId);
        getUserData(mUserId);
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.userstatus_toolbar);
        mToolbarTitle = (TextView) findViewById(R.id.user_status_title);
        tv_user_status_msg = (TextView) findViewById(R.id.tv_user_status_msg);
        right = ((TextView) findViewById(R.id.right));
        if (aIsMe) {
            mToolbarTitle.setText(getResources().getString(R.string.user_item_mytitle));
            tv_user_status_msg.setVisibility(View.VISIBLE);
        } else {
            mToolbarTitle.setText("");
            tv_user_status_msg.setVisibility(View.VISIBLE);
//            if (YNSingleton.getInstance().getCurAlbum().getGcreator().equals(application.getCurID()+"")){
//                right.setVisibility(View.VISIBLE);
//            }
//            if (mUserId==application.getCurID()){
//                right.setVisibility(View.INVISIBLE);
//            }
        }
        setSupportActionBar(mToolbar);
//        right.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(UserStatusActivity.this);
//                builder.setMessage("确定要移除该成员吗？");
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        removeMember();
//                        dialog.dismiss();
//                    }
//                });
//                builder.create().show();
//            }
//        });
        mToolbar.setNavigationIcon(R.drawable.btn_expend_white);
        mAppBar = (AppBarLayout) findViewById(R.id.user_status_appbar);
        collapsing_user_status_toolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_user_status_toolbar);
        rv_user_status_list = (RecyclerView) findViewById(R.id.rv_user_status_list);
        mUserStatusBG = (SimpleDraweeView) findViewById(R.id.iv_user_status_album_top);
        iv_user_status_avatar = (SimpleDraweeView) findViewById(R.id.iv_user_status_avatar);
        tv_user_status_nickname = (TextView) findViewById(R.id.tv_user_status_nickname);
        iv_user_status_sex = (ImageView) findViewById(R.id.iv_user_status_sex);

        mRefreshlayout = (SwipeRefreshLayout) findViewById(R.id.user_status_refresh);
        mRefreshlayout.setColorSchemeColors(Color.parseColor("#fae100"));
        mRefreshlayout.setOnRefreshListener(this);
        mRefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRefreshlayout.setRefreshing(true);
        mLinearLayoutManager = new WrapContentLinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_user_status_list.setLayoutManager(mLinearLayoutManager);
//        mAdapter   = new AlbumStatusAdapter(this,  YNSingleton.getInstance().getStatusList(),aIsMe?2:3);
//        mAdapter = new UesrAlbumStatusAdapter(this, YNSingleton.getInstance().getStatusList(),aIsMe,application.getCurID());
        mAdapter = new TimeLineStatusAdapter(this, groupStatusItems, application.getCurID(), false);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        // rv_user_status_list.setAdapter(mYNRecyclerViewAdapter);
        rv_user_status_list.setAdapter(mAdapter);
        rv_user_status_list.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }
                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_user_status_list);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(UserStatusActivity.this, rv_user_status_list, 10, LoadingFooter.State.Loading, null);
                rv_user_status_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadStatus(false);
                    }
                }, 500);
            }
        });

        //为每个item增加响应事件
//        mAdapter.setOnItemClickListener(new UesrAlbumStatusAdapter.OnItemClickListener() {
//            @Override
//            public void OnItemClick(View view, YNStatus data) {
//                Intent intent = new Intent(UserStatusActivity.this, StatusDetailActivity.class);
//                YNSingleton.getInstance().setCurStatus(data);
//                startActivity(intent);
//            }
//        });
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshlayout.setRefreshing(false);
            }
        }, 500);
    }

//    private void removeMember() {
//        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
//        mParam.put(CommonConstants.YNS_USER_ID,mUserId+"");
//        mParam.put(CommonConstants.YNS_GROUP_ID,mGroupId+"");
//        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/KickMembers")
//                .setMethod(HttpMethods.Post)
//                .setParamMap(mParam)
//                .setHttpListener(new HttpListener<String>(true, false, true) {
//                    @Override
//                    public void onSuccess(String s, Response<String> response) {
//                        YNCommonResponse resRemove = gson.fromJson(s, YNCommonResponse.class);
//                        if (resRemove.getMsg().equals("success")){
//                            showToast("移除成功");
//                            sendBroadcast(new Intent(ACTIONs.remove));
//                            sendBroadcast(new Intent(ACTIONs.deleteMember));
//                        }
//                        finish();
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
//                    }
//                });
//        liteHttp.executeAsync(req);
//    }


    // 更新动态数据
//    private void updateView() {
//        mRefreshlayout.setRefreshing(false);
//        mAdapter.addItemsFromBottom(YNSingleton.getInstance().getStatusList());
//        if (YNSingleton.getInstance().getStatusList().size() == 0) {
//            isBottom = true;
//            RecyclerViewStateUtils.setFooterViewState(this, rv_user_status_list, 10, LoadingFooter.State.TheEnd, null);
//        } else {
//            RecyclerViewStateUtils.setFooterViewState(rv_user_status_list, LoadingFooter.State.Normal);
//        }
//        YNSingleton.getInstance().clearStatusList();
//    }

    private void updateView2(List<YNStatus> statusLists) {
        mRefreshlayout.setRefreshing(false);
        mAdapter.addItemsFromBottom(statusLists);
        if (statusLists.size() == 0) {
            isBottom = true;
            RecyclerViewStateUtils.setFooterViewState(this, rv_user_status_list, 10, LoadingFooter.State.TheEnd, null);
        } else {
            RecyclerViewStateUtils.setFooterViewState(rv_user_status_list, LoadingFooter.State.Normal);
        }
    }

    private void loadStatus(boolean isTop) {
        // 通知后台加载数据
        noticeServiceInit(mUserId, mGroupId, mAdapter.getIdByDirection(isTop));
    }

    // 分析并执行动作
    BroadcastReceiver mUserStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionStatus:
                    boolean isAdd = intent.getExtras().getBoolean(ACTIONs.IsAdd);
                    int statusID = intent.getExtras().getInt(ACTIONs.StatusId);
                    doSyncStatus(isAdd, statusID);
                    break;
                case ACTIONs.actionComment:
                    mAdapter.SyncComment();
                    break;
                case ACTIONs.actionSinglePhoto:
                    mAdapter.notifyDataSetChanged();
                    break;
                case ACTIONs.actionToTimeCardDetail:
                    context.startActivity(new Intent(context, TimeCardDetailActivity.class).putExtra("me", "me").putExtra("lookLimeCard", "lookLimeCard").putExtra("userStatus", true));
                    // overridePendingTransition(R.anim.slide_center_out, R.anim.slide_center_out);
                    break;
                case ACTIONs.modifyStatus:
                    refresh = true;
                    noticeServiceInit(mUserId, mGroupId, 0);
                    break;
            }
        }
    };

    // 同步动态
    private void doSyncStatus(boolean isAdd, int statusID) {
        if (isAdd) {
            if (statusID == YNSingleton.getInstance().getCurStatus().getEid()) {
                mAdapter.addItemsFromTopOne(YNSingleton.getInstance().getCurStatus());
                rv_user_status_list.scrollToPosition(0);
            }
        } else {
            mAdapter.removeOne(statusID);
        }
    }

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionStatus);
        myIntentFilter.addAction(ACTIONs.actionComment);
        myIntentFilter.addAction(ACTIONs.actionSinglePhoto);
        myIntentFilter.addAction(ACTIONs.actionToTimeCardDetail);
        myIntentFilter.addAction(ACTIONs.modifyStatus);
        registerReceiver(mUserStatusBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载数据
    private void noticeServiceInit(int userid, int groupid, int aLoadId) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(groupid));
        mParam.put(CommonConstants.YNS_MIN_ID, String.valueOf(aLoadId));
//        Log.i("xjs", "mpppp===>" + mParam.toString());
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/event/ShowSpaceMemberEvents")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
//                        Log.i("xjs", "userstatus--ssss===>" + s);
                        YNStatusResponse resUserStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (resUserStatus != null && ReqUtils.isSuccess(resUserStatus.getCode())) {
                            List<YNStatus> statusLists = new ArrayList<>();
                            statusLists.addAll(resUserStatus.getData());
                            if (refresh) {
                                mAdapter.update(statusLists);
                                mAdapter.notifyDataSetChanged();
                                refresh = false;
                            } else {
                                updateView2(statusLists);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUserStatusBroadcastReceiver);
    }

    private MenuItem action_set_remark;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setremark, menu);
        action_set_remark = menu.findItem(R.id.action_set_remark);
        if (aIsChat) {
            action_set_remark.setVisible(true);
        } else {
            action_set_remark.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_set_remark:
                Intent intent = new Intent(this, AlertNameActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, tv_user_status_nickname.getText().toString());
                startActivityForResult(intent, CommonConstants.REQ_ALERT_GNAME);
                break;
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //  修改昵称回调
            case CommonConstants.REQ_ALERT_GNAME:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                String albumName_alert = data.getStringExtra(CommonConstants.REQ_DATA);
                tv_user_status_nickname.setText(albumName_alert);
                alertRemarkName(mGroupId, application.getCurID(), mUserId, albumName_alert);
                break;
            default:
                break;
        }
    }

    // 修改备注名
    private void alertRemarkName(int mGroupId, int from, int to, String name) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(mGroupId));
        mParam.put(CommonConstants.FROM, String.valueOf(from));
        mParam.put(CommonConstants.TO, String.valueOf(to));
        mParam.put(CommonConstants.Name, name);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.NoteUserInSpace)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertGroupName = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertGroupName.getCode())) {
                            sendBroadcast(new Intent(ACTIONs.actionNoteNameUpdate));
                            showToast("修改成功");
                        } else {
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        Log.i("xjs", " i===>" + i);
        if (i == 0) {
            mRefreshlayout.setEnabled(true);
//            iv_user_status_avatar.setVisibility(View.VISIBLE);
//            tv_user_status_nickname.setVisibility(View.VISIBLE);
            Log.i("xjs", " mRefreshlayout.setEnabled(true)");
        } else {
//            iv_user_status_avatar.setVisibility(View.INVISIBLE);
//            tv_user_status_nickname.setVisibility(View.INVISIBLE);
            mRefreshlayout.setEnabled(false);
            Log.i("xjs", " mRefreshlayout.setEnabled(false)");
        }
    }


    // 获取成员头信息
    private void getUserTop(int userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNLoginResponse resUser = gson.fromJson(s, YNLoginResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            YNUser user = resUser.getData().get(0);
                            ImageOptHelper.showFrescoAvatar(Uri.parse(YNUrlHelper.getStatusBlur(UserStatusActivity.this, user.getUbackground())), mUserStatusBG, UserStatusActivity.this);
                            avatarPic = user.getUpic();
                            nickname = user.getUnickname();
                            ImageOptHelper.showFrescoAvatar(Uri.parse(YNUrlHelper.getAvatarUrl(UserStatusActivity.this, user.getUpic())), iv_user_status_avatar, UserStatusActivity.this);
                            if (aIsChat) {
                                if (!StringUtils.isEmpty(noteName)) {
                                    tv_user_status_nickname.setText(noteName);
                                } else {
                                    tv_user_status_nickname.setText(user.getUnickname());
                                }
                            } else {
                                tv_user_status_nickname.setText(user.getUnickname());
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void getUserData(int userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = gson.fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            YNUserData ynUserData = resUser.getData().get(0);
                            String album = "0";
                            String photo = "0";
                            String event = "0";
                            if (ynUserData.getAlbum() != null && !ynUserData.getAlbum().equals(""))
                                album = ynUserData.getAlbum();
                            if (ynUserData.getPhoto() != null && !ynUserData.getPhoto().equals(""))
                                photo = ynUserData.getPhoto();
                            if (ynUserData.getEvent() != null && !ynUserData.getEvent().equals(""))
                                event = ynUserData.getEvent();
                            tv_user_status_msg.setText(getResources().getString(R.string.user_album_data1)
                                    + album + getResources().getString(R.string.user_album_data2)
                                    + photo + getResources().getString(R.string.user_album_data3)
                                    + event + getResources().getString(R.string.user_album_data4));
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        mAppBar.addOnOffsetChangedListener(this);
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        mAppBar.removeOnOffsetChangedListener(this);
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "我的回忆_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
